package cn.com.hhrcw.utils;

import cn.hutool.core.io.FileUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @program: recruit-boot-parent
 * @description:
 * @author: JD
 * @create: 2020-11-24 09:52
 **/
@Data
@Slf4j
public class DownloadToZipUtil {

    private DownloadToZipUtil() {}

    /**
     * 通过ISysBaseAPI保存到磁盘
     *
     * @param fileMapList
     * @param zipName
     * @throws IOException
     */
    public static byte[] zipFile(Map<String, File> fileMapList, String zipName) throws IOException {
        zipName = URLEncoder.encode(zipName, StandardCharsets.UTF_8.displayName());
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ZipOutputStream zipOutputStream = new ZipOutputStream(bos)) {
            for (Map.Entry<String, File> entry : fileMapList.entrySet()) {
                String key = entry.getKey();
                File file = entry.getValue();
                if (!file.exists()) {
                    continue;
                }
                ZipEntry zipEntry = new ZipEntry(key);
                zipOutputStream.putNextEntry(zipEntry);
                byte[] bytes = FileUtil.readBytes(file);
                zipOutputStream.write(bytes);
                zipOutputStream.flush();
            }
            zipOutputStream.finish();
            return bos.toByteArray();
        }
    }

    public static void zipFile(OutputStream stream, Map<String, File> fileMapList, String zipName) throws IOException {
        zipName = URLEncoder.encode(zipName, StandardCharsets.UTF_8.name());
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(stream)) {
            for (Map.Entry<String, File> entry : fileMapList.entrySet()) {
                String key = entry.getKey();
                File file = entry.getValue();
                if (!file.exists()) {
                    continue;
                }
                ZipEntry zipEntry = new ZipEntry(key);
                zipOutputStream.putNextEntry(zipEntry);
                byte[] bytes = FileUtil.readBytes(file);
                zipOutputStream.write(bytes);
                zipOutputStream.flush();
            }
            zipOutputStream.flush();
            zipOutputStream.finish();
        } catch (Exception e) {
            log.error(zipName + "压缩错误" + e.getMessage(), e);
        }

    }

    public static void zipFile(HttpServletResponse response, Map<String, File> fileMapList, String zipName) throws IOException {
        zipName = URLEncoder.encode(zipName, "UTF-8");
        // 指明response的返回对象是文件流
        response.setContentType("application/octet-stream");
        // 设置在下载框默认显示的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + zipName + ".zip");
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            for (Map.Entry<String, File> entry : fileMapList.entrySet()) {
                String key = entry.getKey();
                File file = entry.getValue();
                if (!file.exists()) {
                    continue;
                }
                ZipEntry zipEntry = new ZipEntry(key);
                zipOutputStream.putNextEntry(zipEntry);
                byte[] bytes = FileUtil.readBytes(file);
                zipOutputStream.write(bytes);

            }
            zipOutputStream.finish();
        } catch (Exception e) {
            log.error(zipName + "压缩错误" + e.getMessage(), e);
        }

    }

    /**
     * 根据文件，进行压缩，批量下载
     *
     * @param response
     * @param files
     * @param zipName
     * @deprecated
     */
    @Deprecated
    public static void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName) {
        try {
            response.reset();
            zipName = java.net.URLEncoder.encode(zipName, "UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + zipName + ".zip");

            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bos = new BufferedOutputStream(zos);

            for (Map.Entry<String, byte[]> entry : files.entrySet()) {
                //每个zip文件名
                String fileName = entry.getKey();
                //这个zip文件的字节
                byte[] file = entry.getValue();
                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
                zos.putNextEntry(new ZipEntry(fileName));

                int len = 0;
                byte[] buf = new byte[10 * 1024];
                while ((len = bis.read(buf, 0, buf.length)) != -1) {
                    bos.write(buf, 0, len);
                }
                bis.close();
                bos.flush();
            }
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
